package com.hunantv.mglive.ui.discovery.publisher.pic;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ToggleButton;

import com.hunantv.mglive.R;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.Toast;

import java.util.ArrayList;

/**
 * @author maxxiang 图片选择器的adapter
 */
public class PicChooserAdapter extends BaseAdapter implements
		PicQueryMgr.IPicQueryFinished , OnClickListener,OnCheckedChangeListener{

	private Context mContext;
	private ArrayList<PicItem> mPicItems = new ArrayList<PicItem>(); // 所有图片信息(filepath之类的）
	private ArrayList<String> mSelectItems = new ArrayList<String>(); // 选中的图片路径列表
	private AsyncImageLoader mImgLoader = new AsyncImageLoader();
	private PicChooseUICallback mUICallback;
	private int mMaxSelectCount = 9;

	public interface PicChooseUICallback{
		public void updateSelectCount(int count);
		public void goToPreviewMode(int startPosition);
	}

	public PicChooserAdapter(Context ctx, String albumId, PicChooseUICallback callback) {
		super();

		mContext = ctx;
		mUICallback = callback;
		PicQueryMgr.getInstance().queryPicList(albumId, this); // 发起读取相册的请求
	}

	public void setAlbumId(String albumId){
		PicQueryMgr.getInstance().queryPicList(albumId, this);
	}

	public void setMaxSelectCount(int maxSelectCount){
		mMaxSelectCount = maxSelectCount;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mPicItems.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return mPicItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		PicItem item = mPicItems.get(position);
		if (item == null) {
			return null;
		}

		ItemHolder holder = null;
		if (convertView == null) {
			convertView = LayoutInflater.from(mContext).inflate(
					R.layout.publisher_picchooser_item, null);
			holder = new ItemHolder();
			holder.img_thumb = (ImageView) convertView
					.findViewById(R.id.img_thumb);
			holder.img_check = (ToggleButton) convertView
					.findViewById(R.id.img_check);
			convertView.setTag(holder);
		} else {
			holder = (ItemHolder) convertView.getTag();
			convertView.setOnClickListener(null);
			holder.img_check.setOnCheckedChangeListener(null);
			L.d("img", "resused.. grid item...position:" + position + "\n original url:"+ (String)holder.img_thumb.getTag()  +"\n current url:"+item.mPathOrignal);

		}

		holder.position = position;

		Bitmap bm= PicCache.getInstance().getBitmap(item.mPathOrignal);
		if (bm == null) {
			holder.img_thumb.setImageResource(R.drawable.publisher_defaultpic);
			mImgLoader.asyncLoadImage(holder.img_thumb, item.mPathOrignal,position);
		} else {
			holder.img_thumb.setImageBitmap(bm);
			holder.img_thumb.setTag(item.mPathOrignal);
		}

		if (mSelectItems.contains(item.mPathOrignal) == true) {
			holder.img_check.setChecked(true);
		} else {
			holder.img_check.setChecked(false);
		}

		convertView.setOnClickListener(this);
		holder.img_check.setOnCheckedChangeListener(this);
		holder.img_check.setTag(Integer.valueOf(position));

		return convertView;
	}

	@Override
	public void onClick(View v) {

		if(v.getTag() == null || !(v.getTag() instanceof ItemHolder))
			return;

		ItemHolder itemholder = (ItemHolder) v.getTag();
		PicItem item = mPicItems.get(itemholder.position);
		if (item == null) {
			return;
		}

		mUICallback.goToPreviewMode(itemholder.position);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if(!(buttonView instanceof ToggleButton))
				return;
		int position = ((Integer)buttonView.getTag()).intValue();
		PicItem item = mPicItems.get(position);

		if(isChecked){
			if (!mSelectItems.contains(item.mPathOrignal)) {

				if (mSelectItems.size() >= mMaxSelectCount) {

					if (mMaxSelectCount == 1) {
						mSelectItems.clear();
						notifyDataSetChanged();
					} else {
						buttonView.setOnCheckedChangeListener(null);
						buttonView.setChecked(false);
						buttonView.setOnCheckedChangeListener(this);
						Toast toast = Toast.makeText(mContext,
								"已经达到最大可选择的图片数量....", Toast.LENGTH_SHORT);
						toast.show();
						return;
					}
				}

				mSelectItems.add(item.mPathOrignal);
				// ImgMask.setVisibility(View.VISIBLE);

			}
		}
		else{

			if (mSelectItems.contains(item.mPathOrignal)){
				mSelectItems.remove(item.mPathOrignal);
				// ImgMask.setVisibility(View.INVISIBLE);
			}
		}

		mUICallback.updateSelectCount(mSelectItems.size());
	}


	public ArrayList<String> getPicSelectLists() {
		return mSelectItems;
	}

	public void setPicSelectLists(ArrayList<String> list) {
		L.d("preview", "setPicSelectLists size :" + list.size());
		mSelectItems = list;
	}

	public ArrayList<String> getPicLists() {
		ArrayList<String> picList = new ArrayList<String>();
		for(int i = 0 ; i < mPicItems.size() ; i++){
			PicItem item = (PicItem) mPicItems.get(i);
			if(item != null && item.mPathOrignal != null){
				picList.add(item.mPathOrignal);
			}
			else{
				picList.add("");
			}
		}
		return picList;
	}

	
	
/*	maxxiang: fuck,fuck!! asyncTask处理多线程解码的性能好差，不用它了，自已实现一个。
	public interface ImgCallBack {
		public void resultImgCall(ImageView imageView,String imgUrl, Bitmap bitmap);
	}

	public void imgExcute(ImageView imageView,ImgCallBack icb, String... params){
		LoadBitAsynk loadBitAsynk=new LoadBitAsynk(imageView,params[0], icb);
		loadBitAsynk.execute(params);
	}
	public class LoadBitAsynk extends AsyncTask<String, Integer, Bitmap>{

		ImageView imageView;
		ImgCallBack icb;
		String mImgUrl;
		
		LoadBitAsynk(ImageView imageView,String imgUrl, ImgCallBack icb){
			this.imageView=imageView;
			this.icb=icb;
			this.mImgUrl = imgUrl;
		}
		
		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap=null;
			try {
				bitmap = loadImageFromUrl(params[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (result!=null) {
				icb.resultImgCall(imageView, mImgUrl, result);
			}
		}
		
		public Bitmap loadImageFromUrl(String url) {
			Options options = new Options();
			options.inJustDecodeBounds = true;
			//options.inPreferredConfig = Bitmap.Config.ARGB_4444;//URLDrawable.sDefaultDrawableParms.mConfig;
			options.inDensity = DisplayMetrics.DENSITY_DEFAULT;
			options.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
			options.inScreenDensity = DisplayMetrics.DENSITY_DEFAULT;
			BitmapFactory.decodeFile(url, options);

			// 重新decode
			options.inJustDecodeBounds = false;
			options.inSampleSize = calculateInSampleSize(options, PicQueryConstants.RECENT_PHOTO_MIN_WIDTH, PicQueryConstants.RECENT_PHOTO_MIN_WIDTH);
			Bitmap bitmap = BitmapFactory.decodeFile(url, options);
			return bitmap;
		}
		
		private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
		{
			if (reqWidth == 0 || reqHeight == 0 || reqWidth == -1 || reqHeight == -1)
			{
				return 1;
			}
			// Raw height and width of image
			int height = options.outHeight;
			int width = options.outWidth;
			int inSampleSize = 1;

			// 超过1.5倍会被缩放
			while (height > reqHeight && width > reqWidth)
			{
				final int heightRatio = Math.round((float) height / (float) reqHeight);
				final int widthRatio = Math.round((float) width / (float) reqWidth);

				int ratio = heightRatio > widthRatio ? heightRatio : widthRatio;
				if (ratio >= 2)
				{
					width /= 2;
					height /= 2;
					inSampleSize *= 2;
				}
				else
				{
					break;
				}
			}
			return inSampleSize;
		}		
		
		
	}
*/



	@Override
	public void onQueryPicFinished(ArrayList<PicItem> list) {
		// TODO Auto-generated method stub
		mPicItems = list;

		ImgWorkThread.getInstance().getUiHandler().post(notifyRunnable);
	}

	private Runnable notifyRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			notifyDataSetChanged();
		}
	};

	class ItemHolder {
		public ImageView img_thumb;
		public ImageView img_thumb_mask; //被选中时的mask
		public ToggleButton img_check;
		public int position;
	}

	class OnPicClick implements OnClickListener {
		Integer pos;
//		ImageView ImgMask;
		ToggleButton ImgCheck;
		PicItem item;

		public OnPicClick(int position, PicItem item, ToggleButton img_check, ImageView imgMask) {
			this.pos = position;
			this.item = item;
			this.ImgCheck = img_check;
//			this.ImgMask = imgMask;
		}

		@Override
		public void onClick(View v) {

			if (mSelectItems.contains(item.mPathOrignal) != true) {

				if(mSelectItems.size() >=  mMaxSelectCount){

					if(mMaxSelectCount == 1){
						mSelectItems.clear();
						notifyDataSetChanged();
					}
					else{
						Toast toast = Toast.makeText(mContext, "已经达到最大可选择的图片数量....", Toast.LENGTH_SHORT);
						toast.show();
						return;
					}
				}

				mSelectItems.add(item.mPathOrignal);
//				ImgCheck.setVisibility(View.VISIBLE);
//				ImgMask.setVisibility(View.VISIBLE);

			} else {
				mSelectItems.remove(item.mPathOrignal);
//				ImgCheck.setVisibility(View.INVISIBLE);
//				ImgMask.setVisibility(View.INVISIBLE);
			}

			mUICallback.updateSelectCount(mSelectItems.size());

		}
	}


}
